//
//  weatherViewController.swift
//  Community
//
//  Created by JKSD on 2019/7/26.
//  Copyright © 2019 ZKJ. All rights reserved.
//

import UIKit
import CoreLocation

typealias MKPositioningClosure = (String) -> ()




class weatherViewController: UIViewController {
    let PostKey = "18587ba998ea414d942c24e73c174c32"
    
    var NAVH : CGFloat = 0.0
    
    var clousre : MKPositioningClosure?
    
    private var locationManager : CLLocationManager?
   
    var source : NSArray = []
    
    let temLab = UILabel()
    let dateLab = UILabel()
    let infoLab = UILabel()
    let bTemImage = UIImageView()
    let maxMin = UILabel()
    let type = UILabel()
    let zs = UILabel()
    let quaLab = UILabel()
    let desLab = UILabel()
    let titleLab = UILabel()
    
    let tip = UILabel()
    let dayView = UIView()
    let daLa1 = UILabel()
    let daLa2 = UILabel()
    let daLa3 = UILabel()
    let daLa4 = UILabel()
    let dawnView = UIView()
    let wnla1 = UILabel()
    let wnla2 = UILabel()
    let wnla3 = UILabel()
    let wnla4 = UILabel()
    let nightView = UIView()
    let ghla1 = UILabel()
    let ghla2 = UILabel()
    let ghla3 = UILabel()
    let ghla4 = UILabel()
    var requst = 1
    private var viewController : UIViewController?
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requst = 1
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let SH = STABARH
        self.fd_prefersNavigationBarHidden = true
        NAVH = (self.navigationController?.navigationBar.frame.size.height)! + STABARH
   
        self.configureView()
        self.startPositioning(self)
        
        self.titleLab.frame = CGRect (x: 55, y:SH , width: SCREEN_WIDTH - 110, height: NAVH - SH)
        self.titleLab.font = constant .kFontSize(x: 18)
        self.titleLab.textColor = UIColor.white
        self.titleLab.textAlignment = NSTextAlignment.center
        self.view .addSubview(titleLab)
        
        self.dateLab.frame = CGRect (x: 20, y: NAVH + 40, width: SCREEN_WIDTH - 40, height: 20)
        self.dateLab.font = constant.kFontSize(x: 18)
        self.dateLab.textColor = UIColor.white
        self.dateLab.textAlignment = NSTextAlignment.center
        self.dateLab.numberOfLines = 0
        self.view.addSubview(self.dateLab)
        
        self.temLab.frame = CGRect (x: 20, y: dateLab.n_maxY + 10, width: SCREEN_WIDTH - 40, height: 40)
        self.temLab.font = constant.kFontSize(x: 35)
        self.temLab.textColor = UIColor.white
        self.temLab.textAlignment = NSTextAlignment.center
        self.view.addSubview(self.temLab)
        
        self.bTemImage.frame = CGRect (x: (SCREEN_WIDTH - 80)/2.0, y: self.temLab.n_maxY + 10, width: 80, height: 80)
        self.view.addSubview(self.bTemImage)
        
        self.infoLab.frame = CGRect (x: 20, y: self.bTemImage.n_maxY + 10, width: SCREEN_WIDTH - 40, height: 20)
        self.infoLab.font = constant.kFontSize(x: 18)
        self.infoLab.textColor = UIColor.white
        self.infoLab.textAlignment = NSTextAlignment.center
        self.infoLab.numberOfLines = 0
        self.view.addSubview(self.infoLab)
        
        
        
        let back = UIButton(type: UIButton.ButtonType.custom)
        back.frame = CGRect(x: 15,y: NavBarHeight,width: 44,height: 44)
        back.setImage(UIImage.init(named: "back"), for: UIControl.State.normal)
        back.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
        back.addTarget(self, action: #selector(backAct), for: UIControl.Event.touchUpInside)
        self.view.addSubview(back)
    }
   @objc func backAct() {
        self.navigationController?.popViewController(animated: true)
    }
    func configureView() {
        weatherView.weatherBackImageView.frame = self.view.bounds
        self.view.addSubview(weatherView.weatherBackImageView)
        
        weatherView.frame = self.view.bounds
        self.view.addSubview(weatherView)
    }
    lazy var weatherView : WHWeatherView = {
        let weatherView = WHWeatherView()
        return weatherView
    }()
    lazy var fuckView : UIView = {
        let fuckView = UIView.init(frame: CGRect (x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))

        let blur = UIBlurEffect(style: .light)
        //        初始化一个基于模糊效果的视觉效果视图
        let blurView = UIVisualEffectView(effect: blur)
        blurView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        fuckView.addSubview(blurView)
        UIApplication.shared.keyWindow?.addSubview(fuckView)
        
        tip.textColor = UIColor.white
        fuckView.addSubview(tip)
        
        dawnView.frame = CGRect (x: 0, y: SCREEN_HEIGHT - 240, width: SCREEN_WIDTH, height: 80)
        self.wnla1.frame = CGRect (x: 20, y: 0, width: SCREEN_WIDTH - 40, height: 20)
        self.wnla2.frame = CGRect (x: 20, y: 20, width: SCREEN_WIDTH - 40, height: 20)
        self.wnla3.frame = CGRect (x: 20, y: 40, width: SCREEN_WIDTH - 40, height: 20)
        self.wnla4.frame = CGRect (x: 20, y: 60, width: SCREEN_WIDTH - 40, height: 20)
        self.wnla1.textColor = UIColor.white
        self.wnla2.textColor = UIColor.white
        self.wnla3.textColor = UIColor.white
        self.wnla4.textColor = UIColor.white
        self.dawnView.addSubview(self.wnla1)
        self.dawnView.addSubview(self.wnla2)
        self.dawnView.addSubview(self.wnla3)
        self.dawnView.addSubview(self.wnla4)
        fuckView.addSubview(dawnView)
        
        dayView.frame = CGRect (x: 0, y: SCREEN_HEIGHT - 240+80, width: SCREEN_WIDTH, height: 80)
        self.daLa1.frame = CGRect (x: 20, y: 0, width: SCREEN_WIDTH - 40, height: 20)
        self.daLa2.frame = CGRect (x: 20, y: 20, width: SCREEN_WIDTH - 40, height: 20)
        self.daLa3.frame = CGRect (x: 20, y: 40, width: SCREEN_WIDTH - 40, height: 20)
        self.daLa4.frame = CGRect (x: 20, y: 60, width: SCREEN_WIDTH - 40, height: 20)
        self.daLa1.textColor = UIColor.white
        self.daLa2.textColor = UIColor.white
        self.daLa3.textColor = UIColor.white
        self.daLa4.textColor = UIColor.white
        self.dayView.addSubview(self.daLa1)
        self.dayView.addSubview(self.daLa2)
        self.dayView.addSubview(self.daLa3)
        self.dayView.addSubview(self.daLa4)
        fuckView.addSubview(dayView)
        
        nightView.frame = CGRect (x: 0, y: SCREEN_HEIGHT - 240+160, width: SCREEN_WIDTH, height: 80)
        self.ghla1.frame = CGRect (x: 20, y: 0, width: SCREEN_WIDTH - 40, height: 20)
        self.ghla2.frame = CGRect (x: 20, y: 20, width: SCREEN_WIDTH - 40, height: 20)
        self.ghla3.frame = CGRect (x: 20, y: 40, width: SCREEN_WIDTH - 40, height: 20)
        self.ghla4.frame = CGRect (x: 20, y: 60, width: SCREEN_WIDTH - 40, height: 20)
        self.ghla1.textColor = UIColor.white
        self.ghla2.textColor = UIColor.white
        self.ghla3.textColor = UIColor.white
        self.ghla4.textColor = UIColor.white
        self.nightView.addSubview(self.ghla1)
        self.nightView.addSubview(self.ghla2)
        self.nightView.addSubview(self.ghla3)
        self.nightView.addSubview(self.ghla4)
        fuckView.addSubview(nightView)
        
        fuckView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer.init(target: self, action:#selector(remoFuck))
        fuckView.addGestureRecognizer(tap)
        return fuckView
    }()
    @objc func remoFuck() {
        UIView.animate(withDuration: 0.3) {
            self.fuckView.frame = CGRect (x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        }
    }
    // 外部初始化的对象调用，执行定位处理。
    func startPositioning(_ vc:UIViewController) {
        viewController = vc
        if (self.locationManager != nil) && (CLLocationManager.authorizationStatus() == .denied) {
            // 定位提示
            alter(viewController: viewController!)
        } else {
            requestLocationServicesAuthorization()
        }
    }

    // 初始化定位
    private func requestLocationServicesAuthorization() {
        
        if (self.locationManager == nil) {
            self.locationManager = CLLocationManager()
            self.locationManager?.delegate = self as CLLocationManagerDelegate
        }
        
        self.locationManager?.requestWhenInUseAuthorization()
        self.locationManager?.startUpdatingLocation()
        
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined) {
            locationManager?.requestWhenInUseAuthorization()
        }
        
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse) {
            locationManager?.desiredAccuracy = kCLLocationAccuracyBest
            let distance : CLLocationDistance = 10.0
            locationManager?.distanceFilter = distance
            locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager?.startUpdatingLocation()
        }
    }
    
    
    // 获取定位代理返回状态进行处理
    private func reportLocationServicesAuthorizationStatus(status:CLAuthorizationStatus) {
        
        if status == .notDetermined {
            // 未决定,继续请求授权
            requestLocationServicesAuthorization()
        } else if (status == .restricted) {
            // 受限制，尝试提示然后进入设置页面进行处理
            alter(viewController: viewController!)
        } else if (status == .denied) {
            // 受限制，尝试提示然后进入设置页面进行处理
            alter(viewController: viewController!)
        }
    }
    
    
    private func alter(viewController:UIViewController) {
       let alert = UIAlertController.init(title: "定位服务未开启,是否前往开启?", message: "请进入系统[设置]->[隐私]->[定位服务]中打开开关，并允许“赏金猎人”使用定位服务", preferredStyle: UIAlertController.Style.alert)
        
        let action = UIAlertAction.init(title: "YES", style: UIAlertAction.Style.default) { (act) in
            let url = URL(fileURLWithPath: UIApplication.openSettingsURLString)
            if UIApplication.shared.canOpenURL(url){
                UIApplication.shared.openURL(url)
            }
        }
        let action1 = UIAlertAction.init(title: "NO", style: UIAlertAction.Style.default) { (UIAlertAction) in
            
        }
        alert.addAction(action)
        alert.addAction(action1)
        self.present(alert, animated: true, completion: nil)
    }
}

extension weatherViewController:  CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.locationManager?.stopUpdatingLocation()
        
        let location = locations.last ?? CLLocation()
        let geocoder = CLGeocoder()
        
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in

            if error != nil {
                if self.clousre != nil {
                    self.clousre!(error?.localizedDescription ?? "")
                }
                return
            }

            if let place = placemarks?[0]{
                
                // 国家 省  市  区  街道  名称  国家编码  邮编
                //                let country = place.country ?? ""
                let lo:String = (place.locality != nil) ? place.locality! : "东莞"
                let locality = "https://www.tianqiapi.com/api/?appid=24198181&appsecret=s53KVi1R&version=v1&city=" + lo
                self.titleLab.text =  (place.locality != nil) ? place.locality : "东莞"
                self.requst += 1
                if self.requst == 2{
                    NetWorkRequest.sharedInstance.postWithRequest(UrlString:locality , paramer: nil, success: { (obj:Dictionary) in
                        
                    self.source = weatherModel.mj_objectArray(withKeyValuesArray: obj["data"])
                        
                    let model = self.source.firstObject as! weatherModel
                        self.dateLab.text = model.day
                        if model.wea.contains("雨"){
                            self.bTemImage.image = UIImage.init(named: "1184220")
                            self.weatherView.showWeatherAnimation(with: WHWeatherType.rain)
                        }
                        if model.wea.contains("云"){
                            self.bTemImage.image = UIImage.init(named: "1184166")
                            self.weatherView.showWeatherAnimation(with: WHWeatherType.clound)
                        }
                        if model.wea.contains("阴"){
                            self.bTemImage.image = UIImage.init(named: "1184166")
                            self.weatherView.showWeatherAnimation(with: WHWeatherType.clound)
                        }
                        if model.wea.contains("晴"){
                            self.bTemImage.image = UIImage.init(named: "1184185")
                            self.weatherView.showWeatherAnimation(with: WHWeatherType.sun)
                        }
                        if model.wea.contains("雪"){
                            self.bTemImage.image = UIImage.init(named: "1184211")
                            self.weatherView.showWeatherAnimation(with: WHWeatherType.snow)
                        }
                        if model.wea.contains("雷"){
                            self.bTemImage.image = UIImage.init(named: "1184239")
                            self.weatherView.showWeatherAnimation(with: WHWeatherType.rainLighting)
                        }
                        self.temLab.text = model.tem2 + "/" + model.tem1
                        self.infoLab.text = model.air_tips
                        self.infoLab.numberOfLines = 0
                        self.infoLab.sizeToFit()
                        self.fourDays(source: self.source)
                    }, failure: { (error) in
                        LYProgressHUD.showMessage("没查到当前天气数据~")
                        self.infoLab.text = "水光潋滟晴方好，山色空蒙雨亦奇。/n欲把西湖比西子，淡妆浓抹总相宜。";
                        self.infoLab.sizeToFit()
                    })
                }

            }
        }
    }
    @objc func clickOnView(tap:UITapGestureRecognizer) {
        let index = tap.view?.tag
        let model = self.source[index! + 1 ] as! weatherModel
        let vc = WeatherDetailViewController()
        vc.weather = model
        self.navigationController?.pushViewController(vc, animated: true)
    
    }

    func fourDays(source:NSArray) {
        var index = 0;
        for i in 0...1 {
            for j in 0...2{
                index += 1
                let model = source[index]
                let weatherView = WeatherView.init(frame: CGRect (x:CGFloat(j) * SCREEN_WIDTH/3.0 , y: SCREEN_HEIGHT - NAVH - 200 + CGFloat(i) * CGFloat(100 + 10), width: SCREEN_WIDTH/3.0, height: 100))
                self.view.addSubview(weatherView)
                weatherView.tag = i
                let tap = UITapGestureRecognizer.init(target: self, action: #selector(self.clickOnView(tap:)))
                weatherView.isUserInteractionEnabled = true
                weatherView.addGestureRecognizer(tap)
                weatherView.fillView(model: model as! weatherModel)
            }
        }
        for i in 0...source.count - 1 {
            let model = source[i]
            
        }
    }
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        reportLocationServicesAuthorizationStatus(status: status)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        self.locationManager?.stopUpdatingLocation()
    }
}



